<template>
  <div class="app-container">
    <div class="container-module">
      <el-row :gutter="20">
        <el-col>
          <el-form :inline="true" class="search-form">
            <el-form-item>
              <el-button
                class=""
                type="primary"
                icon="el-icon-circle-plus-outline"
                @click="add()"
                >添加菜单</el-button
              >
            </el-form-item>
            <el-form-item style="float: right">
              <el-button
                v-if="isExpandAll"
                class="filter-item"
                type="warning"
                icon="el-icon-caret-bottom"
                @click="expandAll(!isExpandAll)"
                >展开</el-button
              >
              <el-button
                v-else
                class="filter-item"
                type="warning"
                icon="el-icon-caret-top"
                @click="expandAll(!isExpandAll)"
                >收缩</el-button
              >
              <el-button
                class="filter-item"
                type="primary"
                icon="el-icon-refresh"
                @click="refresh()"
                >刷新</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
        <el-col class="marginTop">
          <!-- 列表 -->
          <el-table
            ref="tableRef"
            v-loading="loading"
            :data="datas"
            :max-height="height + 60"
            style="width: 100%"
            row-key="id"
          >
            <el-table-column prop="name" label="名称" min-width="200" />
            <el-table-column
              prop="app"
              label="应用"
              min-width="80"
              align="center"
            />
            <el-table-column
              prop="controller"
              label="控制器"
              min-width="140"
              align="center"
            />
            <el-table-column
              prop="action"
              label="操作"
              min-width="80"
              align="center"
            />
            <el-table-column
              prop="route"
              label="路由"
              min-width="140"
              align="center"
            />
            <el-table-column
              prop="icon"
              label="图标"
              min-width="70"
              align="center"
            >
              <template slot-scope="scope">
                <i v-if="scope.row.icon" :class="scope.row.icon" />
              </template>
            </el-table-column>
            <el-table-column
              prop="status"
              label=""
              min-width="85"
              align="center"
            >
              <template slot="header">
                <span>是否禁用</span>
                <el-tooltip placement="top">
                  <div slot="content">禁用后无法访问</div>
                  <i class="el-icon-warning" title="" />
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  :active-value="1"
                  :inactive-value="2"
                  @change="isActivate(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="sorting"
              label="排序"
              min-width="75"
              align="center"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.sorting"
                  type="text"
                  placeholder=""
                  @blur.native.capture="listOrders(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              min-width="220"
              align="center"
              fixed="right"
            >
              <template slot-scope="{ row }">
                <el-button type="primary" size="mini" @click="add(row)"
                  >添加子菜单</el-button
                >
                <el-button type="primary" size="mini" @click="edit(row)"
                  >编辑</el-button
                >
                <el-button type="danger" size="mini" @click="del(row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>
    <!-- 添加、修改 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      top="10vh"
      width="800px"
      :close-on-click-modal="false"
      :before-close="cancel"
    >
      <el-form
        v-loading="loading"
        ref="formRef"
        :rules="rules"
        :model="model"
        class=""
        label-width="100px"
        :inline="true"
      >
        <el-form-item label="上一级" prop="parent_id" style="width: 100%">
          <el-cascader
            v-model="model.parent_id"
            :options="treeDatas"
            :props="props"
            placeholder="一级菜单"
            clearable
            filterable
            @change="pickParentId"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="model.name" placeholder="请输入名称" clearable />
        </el-form-item>
        <el-form-item label="应用" prop="app">
          <el-input v-model="model.app" placeholder="区分大小写" clearable />
        </el-form-item>
        <el-form-item label="控制器" prop="controller">
          <el-input
            v-model="model.controller"
            placeholder="区分大小写"
            clearable
          />
        </el-form-item>
        <el-form-item label="操作" prop="action">
          <el-input v-model="model.action" placeholder="区分大小写" clearable />
        </el-form-item>
        <el-form-item label="前端路由" prop="route">
          <el-input v-model="model.route" placeholder="区分大小写" clearable />
        </el-form-item>
        <el-form-item label="是否是路由" prop="is_route">
          <el-radio-group v-model="model.is_route">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="类型" prop="type" style="width: 100%">
          <el-radio-group v-model="model.type">
            <el-radio
              v-for="item in types"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图标" prop="icon" style="width: 100%">
          <el-input v-model="model.icon" class="" placeholder="" clearable>
            <el-button
              v-if="model.icon"
              slot="append"
              :icon="model.icon"
              @click="iconDialog = true"
            ></el-button>
            <el-button v-else slot="append" @click="iconDialog = true"
              >选择</el-button
            >
          </el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sorting">
          <el-input-number
            v-model="model.sorting"
            :min="1"
            :max="99999"
            step-strictly
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-switch
            v-model="model.status"
            :active-value="1"
            :inactive-value="2"
          ></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button :loading="btnLoading" type="primary" @click="submit"
          >提交</el-button
        >
      </div>
    </el-dialog>

    <!--图标管理 -->
    <el-dialog
      class="icon-dialog"
      :title="iconTitle"
      :visible.sync="iconDialog"
      width="80%"
      top="10vh"
    >
      <icon-manage @cancelCallback="iconCancel" @submitCallback="iconSubmit" />
    </el-dialog>
  </div>
</template>

<script>
import screenHeight from "@/utils/screen-height";
import IconManage from "@/views/admin/iframe/components/Icon";
import { disabledTree } from "@/utils/index";
import { list, info, save, del, disable, listOrders } from "@/api/admin/menu";

export default {
  name: "AdminAdminmenu",
  components: { IconManage },
  directives: {},
  data() {
    return {
      name: "菜单",
      height: 680,
      loading: false,
      datas: [],
      dialogVisible: false,
      dialogTitle: "",
      btnLoading: false,
      model: {
        id: "",
        created_at: "",
        updated_at: "",
        parent_id: 0,
        name: "",
        app: "",
        controller: "",
        action: "",
        route: "",
        is_route: 1,
        type: 1,
        icon: "",
        sorting: 100,
        status: 1, // :active-value 前面要加：否则不能识别出数据，会认为"1"是字符串
      },
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        app: [{ required: true, message: "请输入应用", trigger: "blur" }],
        controller: [
          { required: true, message: "请输入控制器", trigger: "blur" },
        ],
      },
      props: {
        checkStrictly: true,
        children: "children",
        value: "id",
        label: "name",
      },
      isExpandAll: true,
      treeDatas: [],

      types: [
        { value: 1, label: "模块" },
        { value: 2, label: "列表" },
        { value: 3, label: "操作" },
      ],

      iconDialog: false,
      iconTitle: "图标管理",
    };
  },
  created() {
    this.height = screenHeight();
    this.list();
  },
  methods: {
    // 列表
    list() {
      this.loading = true;
      list()
        .then((res) => {
          this.datas = res.data.data;
          this.treeDatas = res.data.data;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 添加
    add(row) {
      this.dialogVisible = true;
      this.dialogTitle = "新增";
      this.model = this.$options.data().model;
      // object（对象）array（数组）这两个类型进行等于赋值的时候实际上是进行的引用，源数据改变后目标数据也就发生了变换
      //this.treeDatas = this.datas // 原始的的数据是一个数组或者对象，对于一个对象或者数组的时候他们等于是引用的地址是相同的，所以treeDatas改变时datas也会跟着改变
      this.treeDatas = JSON.parse(JSON.stringify(this.datas));
      if (row) {
        this.model.parent_id = row.id;
      }
    },
    // 修改
    edit(row) {
      this.loading = true;
      this.dialogVisible = true;
      this.dialogTitle = "编辑：" + row.name;
      this.treeDatas = disabledTree(
        JSON.parse(JSON.stringify(this.datas)),
        row.id
      );
      info({
        id: row.id,
      })
        .then((res) => {
          this.reset(res.data);
          console.log(1);
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 删除
    del(row) {
      this.$confirm(
        '确定要删除ID： <span style="color:red">' +
          row.id +
          " </span> 这条数据吗？",
        "ID：" + row.id,
        { type: "warning", dangerouslyUseHTMLString: true }
      )
        .then(() => {
          this.loading = true;
          del({
            id: row.id,
          })
            .then((res) => {
              this.list();
              this.reset();
              this.$messages.success(res.msg);
            })
            .catch(() => {
              this.loading = false;
            });
        })
        .catch(() => {});
    },
    // 取消
    cancel() {
      this.reset();
      this.dialogVisible = false;
    },
    // 提交
    submit() {
      this.$refs["formRef"].validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          this.model.parent_id = this.getParentId(this.model.parent_id);
          save(this.model, "post")
            .then((res) => {
              this.btnLoading = false;
              this.list();
              this.dialogVisible = false;
              this.$messages.success(res.msg);
            })
            .catch(() => {
              this.btnLoading = false;
            });
        }
      });
    },
    // 重置
    reset(row) {
      if (row) {
        this.model = row;
      } else {
        this.model = this.$options.data().model;
      }
      if (this.$refs["formRef"] !== undefined) {
        this.$refs["formRef"].resetFields();
      }
    },
    // 刷新
    refresh() {
      this.list();
    },

    // 更新排序
    listOrders(row) {
      listOrders({
        ids: row.id,
        sorting: row.sorting,
      })
        .then((res) => {
          this.$messages.success(res.msg);
        })
        .catch(() => {});
    },

    // 展开/收起
    expandAll(e) {
      this.isExpandAll = e;
      this.expandFor(this.datas, !e);
    },
    expandFor(data, isExpand) {
      data.forEach((i) => {
        this.$refs.tableRef.toggleRowExpansion(i, isExpand);
        if (i.children) {
          this.expandFor(i.children, isExpand);
        }
      });
    },
    // 启用/禁用
    isActivate(row) {
      this.loading = true;
      disable({
        id: row.id,
        status: row.status,
      })
        .then((res) => {
          this.list();
          this.$messages.success(res.msg);
        })
        .catch(() => {
          this.list();
        });
    },
    // 父级选择
    pickParentId(value) {
      if (value) {
        //this.model.parent_id = this.getParentId(value)
      }
    },
    getParentId(ids) {
      if (Array.isArray(ids)) {
        // 取数组最后一项的值
        return ids[ids.length - 1];
      } else {
        return ids;
      }
    },

    iconCancel() {
      this.iconDialog = false;
    },
    iconSubmit(icon) {
      this.model.icon = icon;
      this.iconDialog = false;
    },
  },
};
</script>

<style lang="scss">
.icon-dialog {
  .el-dialog__body {
    padding: 20px 10px;
  }
}
</style>
